package com.web.cookTest;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet(urlPatterns = "/cookie01")
public class CookieTest01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置返回值的编码格式
        resp.setContentType("text/html;charset=utf-8");
        //获取cookies数组
        Cookie[] cookies = req.getCookies();
        //获取用户最后一次访问时间
        Cookie cookie = getCookie(cookies, "lasttime");

        /**
         * 值为空-->第一次访问记录本次访问的时间
         * 值不为空-->获取上次访问时间，记录本次访问时间
         */
        if (cookie != null) {
            String lasttime = cookie.getValue();
            Date date = new Date(Long.parseLong(lasttime));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = sdf.format(date);
            resp.getWriter().write("上次访问"+time);
            cookie.setValue(new Date().getTime()+"");
        }else {
            resp.getWriter().write("第一次访问");
            cookie=new Cookie("lasttime",new Date().getTime()+"");
        }
        //返回cookie值，更新客户端数据
        resp.addCookie(cookie);
    }

    /**
     *
     * @param cookies cookie数组
     * @param cookieName cookie的名称
     * @return 从cookie数组中获取到的指定的cookie值
     */
    private Cookie getCookie(Cookie[] cookies, String cookieName) {
        if (cookies != null) {
            for (Cookie cookie:cookies){
                if (cookie.getName().equals(cookieName)){
                    return cookie;
                }
            }
            return null;
        }
        return null;
    }
}
